package com.beiye.drivertransport.SubActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.frame.view.linearlistview.LinearListView;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.Video.JZMediaIjk;
import com.beiye.drivertransport.Video.MyJZVideoPlayerStandard;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.adapter.CourseDetailSubjectApt;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.CourseDetailBean;
import com.beiye.drivertransport.bean.CourseDetailSubjectBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.SignBean;
import com.beiye.drivertransport.bean.SpecifiedLearningBusinessBean;
import com.beiye.drivertransport.bean.UserTcPhoto;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.thirdparty.tbs.SuperFileView2;
import com.beiye.drivertransport.utils.FileParseUtil;
import com.beiye.drivertransport.utils.HelpUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.beiye.drivertransport.view.CircularProgressView;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.squareup.picasso.Picasso;

import net.frakbot.jumpingbeans.JumpingBeans;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;


import butterknife.OnClick;
import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

//企业管理人员和单位管理人员详情提交
public class SpecifiedLearningBusinessDetailsActivity extends TwoBaseAty  implements SurfaceHolder.Callback{

     WebView web;

     LinearLayout le_parement;

     ImageView img_Courseback;

     LinearListView lv_coursedetail;

     MyJZVideoPlayerStandard jcVideoPlayerStandard;

     TextView tv_courseName;


     TextView tv_courseLength;

     LinearLayout le_course;//隐藏照片
     //    @Bind(R.id.tv_course3)
//    Chronometer tv_cumulativeLength;//累计时长

     TextView tv_cumulativeLength;//累计时长


     ImageView show_camera_iv;//显示照片

     ImageView show_camera_iv1;//显示照片

     SurfaceView surfaceSv;//预览照片

     TextView tv_sure;

     RelativeLayout re_course;//隐藏按钮
     //    @Bind(R.id.re_course1)
//    RelativeLayout re_course1;//照片布局

     TextView img_course;

    TextView tv_course11;//请回答


    SuperFileView2 mSuperFileView;
    private JumpingBeans jumpingBeans2;
    private PopupWindow mDownloadPopWindow;

     private TextView mOffTextView;
     private static final String TAG = SpecifiedLearningBusinessDetailsActivity.class.getSimpleName();
     private static final int MEDIA_TYPE_IMAGE = 1;
     private Timer mOffTime;
     private boolean isloob=true;
     private long mRecordTime;
     private TimerTask timerTask;
     private Handler mOffHandler = new Handler() {
         public void handleMessage(Message msg) {
             if (msg.what > 0) {
                 ////动态显示倒计时
                 downtime.setText(msg.what+"");
             } else {
                 ////倒计时结束自动关闭
                 if (mPopWindow != null) {
                     downtime.setText(msg.what+"");
                     mPopWindow.dismiss();

                     if(!SpecifiedLearningBusinessDetailsActivity.this.isFinishing())
                     {

                         ShowSorryPopwindow();
                     }

                 }
                 // off();////关闭后的操作
                 mOffTime.cancel();
             }
             super.handleMessage(msg);
         }
     };


    private int formattimecnt;
    Handler mHandler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
             super.handleMessage(msg);
             int what = msg.what;
             if (what == 0) {
                 ////打开界面时累计时长
//                tv_cumulativeLength.setBase(SystemClock.elapsedRealtime());
//                int hour = (int) ((SystemClock.elapsedRealtime() - tv_cumulativeLength.getBase()) / 1000 / 60);
//                tv_cumulativeLength.setFormat("0" + String.valueOf(hour) + ":%s");
//                tv_cumulativeLength.start();
//                tv_cumulativeLength.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
//
//
//                    @Override
//                    public void onChronometerTick(Chronometer chronometer) {
//                        String format = chronometer.getText().toString();
//
//                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                Context.MODE_PRIVATE);
//                        SharedPreferences.Editor edit = sp.edit();
//                        edit.putString("format", format);
//                        edit.commit();
//                        String duration = sp.getString("duration", "");
//                        LogUtils.e("format", format);
//                        LogUtils.e("duration", duration);
//                        if (format.equals(duration)) {
//
//                            tv_cumulativeLength.stop();
//
//                            mRecordTime = SystemClock.elapsedRealtime();
//
//                            Intent  intent= new Intent(SpecifiedLearningCourseDetailsActivity.this,TakePictureActivity.class);
//                            startActivityForResult(intent, 0);
//                         //   initDialog();
//                        }
//                    }
//                });
                 SharedPreferences sp1 = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                         Context.MODE_PRIVATE);

                 String format = sp1.getString("format", "");
                 if (format.equals("")) {
                     timerTask = new TimerTask() {
                         int cnt = 0;
                         @Override
                         public void run() {
                             runOnUiThread(new Runnable() {
                                 @Override
                                 public void run() {
                                     String stringTime = getStringTime(cnt++);
                                     tv_cumulativeLength.setText(stringTime);
                                     SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                                             Context.MODE_PRIVATE);
                                     String firsttimestr = getStringTime(firsttime);
                                     SharedPreferences.Editor edit = sp.edit();
                                     edit.putString("format", stringTime);
                                     edit.putString("firsttime", firsttimestr);
                                     edit.commit();
                                     LogUtils.e("format", stringTime);
                                     LogUtils.e("firsttime1", firsttimestr);
                                     //         LogUtils.e("duration", duration);


                                     if (stringTime.equals(firsttimestr)) {
                                         timerTask.cancel();
                                         initDialog();

//                                  JZVideoPlayer jzvd = JZVideoPlayerManager.getCurrentJzvd();
//                                  if(jzvd!=null) {
//                                      jzvd.onStatePause();
//                                      JZMediaManager.pause();//暂停
//                                  }
                                     }
                                 }
                             });
                         }
                     };
                     timer1.schedule(timerTask, 0, 1000);
                 }else {
                     String[] splitformat = format.split(":");
                     String format1 = splitformat[0];
                     String format2 = splitformat[1];
                     String format3 = splitformat[2];
                     int iformat1 = Integer.valueOf(format1);//转int
                     int iformat2 = Integer.valueOf(format2);//转int
                     int iformat3 = Integer.valueOf(format3);//转int
                     int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;
                     formattimecnt = formattime;
                     timerTask = new TimerTask() {
                         @Override
                         public void run() {
                             runOnUiThread(new Runnable() {
                                 @Override
                                 public void run() {
                                     int numTime = formattimecnt++;
                                     String stringTime = getStringTime(numTime);
                                     tv_cumulativeLength.setText(stringTime);
                                     SharedPreferences sp1 = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                                             Context.MODE_PRIVATE);
                                     String firsttimestr1 = getStringTime(firsttime1);
                                     LogUtils.e("format", stringTime);
                                     LogUtils.e("firsttime2", firsttimestr1);
                                     SharedPreferences.Editor edit = sp1.edit();
                                     edit.putString("format", stringTime);
                                     edit.putString("firsttime", firsttimestr1);
                                     edit.commit();
                                     String imgurl = sp1.getString("imgurl", "");
                                     if (imgurl.equals("")) {
                                         if (stringTime.equals(firsttimestr1)) {
                                             timerTask.cancel();
                                             //tv_pause.setVisibility(View.GONE);
                                             initDialog2();
                                         }
                                     } else {

                                         int courseLength = sp1.getInt("courseLength", 0);
                                         int courseLengthtime = courseLength * 60;
                                         String courseLengthtime1 = getStringTime(courseLengthtime);
                                         LogUtils.e("退出拍照后计时", stringTime);
                                         if (stringTime.equals(courseLengthtime1)) {
                                             timerTask.cancel();
                                         }
                                     }

                                 }
                             });
                         }
                     };
                     timer1.schedule(timerTask, 0, 1000);
                 }

             }
             else if (what == 1) {
                 WebSettings settings = web.getSettings();
                 settings.setSavePassword(false);
                 settings.setSaveFormData(false);
                 web.removeJavascriptInterface("accessibility");
                 web.removeJavascriptInterface("accessibilityTraversal");
                 settings.setAllowFileAccessFromFileURLs(false);
                 // 允许使用脚本语言
                 settings.setJavaScriptEnabled(true);
                 // 支持缩放
                 settings.setSupportZoom(true);
                 //  mWebView.addJavascriptInterface(new JavaScriptinterface(BannerItemAty.this), "android");
                 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                     settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                 }//Android 5.0中使用webView 加载网页不显示图片问题
                 // 在当前应用加载网页(直接加载网页不经过浏览器）
                 web.setWebViewClient(new WebViewClient() {
                     @Override // 开始加载网页时触发
                     public void onPageStarted(WebView view, String url, Bitmap favicon) {
                         super.onPageStarted(view, url, favicon);

                     }

                     @Override // 网页加载完成之后触发
                     public void onPageFinished(WebView view, String url) {

                         super.onPageFinished(view, url);

                     }
                 });
                 SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                         Context.MODE_PRIVATE);
                 int tcsn = sp.getInt("tcsn", 0);
                 web.loadUrl(AppInterfaceConfig.BASE_URL + "app/course/content?" + "sn=" + tcsn);

                 // 显示进度
                 web.setWebChromeClient(new WebChromeClient() {
                     @Override // 加载网页进度改变时触发
                     public void onProgressChanged(WebView view, int newProgress) {

                         super.onProgressChanged(view, newProgress);
                     }
                 });
             }
         }
     };
     private CourseDetailSubjectApt courseDetailSubjectApt;
     private Camera mCamera;
     private SurfaceHolder mHolder;
     private PopupWindow mPopWindow;
     private long rangeTime;
     private FileInputStream fStream;

    private ArrayList<CourseDetailSubjectBean.RowsBean> rowscourseList=new ArrayList<>();
     private Timer timer1;

     private int firsttime;

     private int subformatTurnSecond;
     private SensorManager sensorManager;
     private Jzvd.JZAutoFullscreenListener sensorEventListener;

     private TextView downtime;
     private PopupWindow mSorryPopWindow;
     //  private CustomProgressDialog mdialog;
     private ProgressDialog mProgressDialog;
    private int firsttime1;
    private PopupWindow mPopWindow2;


    @Override
     public int getLayoutId() {
         return R.layout.activity_specified_learning_business_details;
    }
    private String getStringTime(int cnt) {
        int hour = cnt/3600;
        int min = cnt % 3600 / 60;
        int second = cnt % 60;
        return String.format(Locale.CHINA,"%02d:%02d:%02d",hour,min,second);
    }
    private String getNumTime(int cnt) {
        int hour = cnt/3600;
        int min = cnt % 3600 / 60;
        int second = cnt % 60;
        if(hour==0)
        {

            return String.format(Locale.CHINA,"%02d分%02d秒",min,second);
        }else{

            return String.format(Locale.CHINA,"%02d小时%02d分%02d秒",hour,min,second);
        }
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_Courseback) {
            TiShiDialog.Builder builder = new TiShiDialog.Builder(this);
            builder.setMessage("点放弃,将自动放弃本课程学习记录");
            builder.setTitle("提示:");
            builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
//                        SharedPreferences spp = getSharedPreferences("imgurl",
//                                Context.MODE_PRIVATE);
//                        SharedPreferences.Editor editor = spp.edit();
//                        editor.clear();
//                        editor.commit();
                    SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.clear();
                    edit.commit();
                    timerTask.cancel();
                    timer1.cancel();
                    timerTask = null;
                    timer1 = null;
                    dialog.dismiss();
                    finish();
                    //设置你的操作事项
                }
            });

            builder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

            builder.create().show();
        } else if (id == R.id.tv_course10) {//提交
            if (Utils.isFastClicker()) {
                return;
            }
            SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                    Context.MODE_PRIVATE);
            String format = sp.getString("format", "");
            int num = sp.getInt("num", 0);
            int tcsn = sp.getInt("tcsn", 0);
            int readInterval = sp.getInt("readInterval", 0);
            int minPer = sp.getInt("minPer", 0);
            int atcSn = sp.getInt("atcSn", 0);
            int atpSn = sp.getInt("atpSn", 0);
            String orgId = sp.getString("orgId", "");


            String[] splitformat = format.split(":");
            String format1 = splitformat[0];
            String format2 = splitformat[1];
            String format3 = splitformat[2];
            int iformat1 = Integer.valueOf(format1);//转int
            int iformat2 = Integer.valueOf(format2);//转int
            int iformat3 = Integer.valueOf(format3);//转int
            int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;
            if (formattime < num) {

                String numTime = getNumTime(num);
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                builder1.setMessage("学习时间不足，不能提交。");
                builder1.setTitle("提示:");
                builder1.setPositiveButton("继续学习", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置你的操作事项
                    }
                });

                builder1.create().show();

            } else {

                if (rowscourseList.size() != 0) {

                    for (int i = 0; i < rowscourseList.size(); i++) {
                        if (rowscourseList.get(i).isSelect() == false) {
                            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                            builder1.setMessage("未作答,请答题");
                            builder1.setTitle("提示:");
                            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    //设置你的操作事项
                                }
                            });

                            builder1.create().show();
                            return;
                        } else {

                            if (rowscourseList.get(i).isLOOP() == false) {
                                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                                builder1.setMessage("回答错误,请重新答题");
                                builder1.setTitle("提示:");
                                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        //设置你的操作事项
                                    }
                                });
                                builder1.create().show();

                                return;
                            }
                        }
                    }
                    //有题目调提交接口
//                        SharedPreferences spp = getSharedPreferences("imgurl",
//                                Context.MODE_PRIVATE);
                    //      int readLength = (formattime%60==0)?formattime/60:(formattime/60+1);//累计学习时间
                    int readLength = (formattime % 60 == 0) ? formattime / 60 : (formattime / 60);//累计学习时间
                    LogUtils.e("readLength", readLength + "");
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    String userId = userInfo.getData().getUserId();//useid
//                        Integer minPer = userInfo.getMinPer();//所属行政区划学习时长最低百分比
                    String imgurl = sp.getString("imgurl", "");//第一次拍照图片地址获取
                    if (imgurl.equals("")) {
                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                        builder1.setMessage("请等待拍照");
                        builder1.setTitle("提示:");
                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //设置你的操作事项
                            }
                        });

                        builder1.create().show();
                        return;
                    }
                    String firsttime = sp.getString("firsttime", "");//第一次抓拍时间
//                        String imgurl1 = spp.getString("imgurl1", "");//第二次拍照图片地址获取
//                        String duration = sp.getString("duration", "");//第二次抓拍时间
                    List<UserTcPhoto> photoList = new ArrayList<UserTcPhoto>();
                    String firsttimesub = firsttime.substring(3, 8);//截取字符串00:00:00变成00:00
                    //                     String durationsub = duration.substring(3, 8);//截取字符串00:00:00变成00:00
                    UserTcPhoto userTcPhoto = new UserTcPhoto();
                    userTcPhoto.setSnapTime(firsttimesub);
                    userTcPhoto.setUrl(imgurl);
                    photoList.add(userTcPhoto);
//                        if(!imgurl1.equals(""))
//                        {
//                        UserTcPhoto userTcPhoto1 = new UserTcPhoto();
//                        userTcPhoto1.setSnapTime(durationsub);
//                        userTcPhoto1.setUrl(imgurl1);
//                        photoList.add(userTcPhoto1);
//                        }
                    Gson gson = new Gson();
                    String strphotoList = gson.toJson(photoList);
                    LogUtils.e("strphotoList", strphotoList);
                    //   showLoadingDialog("提交中");
                    //      setHasAnimiation(false);
//                        mdialog = CustomProgressDialog.show(SpecifiedLearningCourseDetailsActivity.this, "提交中...", false, null);
                    mProgressDialog = new ProgressDialog(SpecifiedLearningBusinessDetailsActivity.this, ProgressDialog.THEME_HOLO_DARK);
                    mProgressDialog.setMessage("提交中...");
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.show();
                    new Login().getSureCosrseAndBusinessLearn(userId, orgId, tcsn, atpSn, atcSn + "", readInterval, minPer, photoList, this, 3);

                } else {//没有题目调提交接口
                    //  int readLength = (formattime%60==0)?formattime/60:(formattime/60+1);//累计学习时间
                    int readLength = (formattime % 60 == 0) ? formattime / 60 : (formattime / 60);//累计学习时间
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    String userId = userInfo.getData().getUserId();//useid
//                        Integer minPer = userInfo.getMinPer();//所属行政区划学习时长最低百分比
//                        SharedPreferences spp = getSharedPreferences("imgurl",
//                                Context.MODE_PRIVATE);
                    String imgurl = sp.getString("imgurl", "");//第一次拍照图片地址获取
                    if (imgurl.equals("")) {
                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                        builder1.setMessage("请等待拍照");
                        builder1.setTitle("提示:");
                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //设置你的操作事项
                            }
                        });

                        builder1.create().show();
                        return;
                    }

                    String firsttime = sp.getString("firsttime", "");//第一次抓拍时间
//                        String imgurl1 = spp.getString("imgurl1", "");//第二次拍照图片地址获取
//                        String duration = sp.getString("duration", "");//第二次抓拍时间
                    String firsttimesub = firsttime.substring(3, 8);//截取字符串00:00:00变成00:00
                    //                       String durationsub = duration.substring(3,8);//截取字符串00:00:00变成00:00
                    List<UserTcPhoto> photoList = new ArrayList<UserTcPhoto>();
                    UserTcPhoto userTcPhoto = new UserTcPhoto();
                    userTcPhoto.setUrl(imgurl);
                    userTcPhoto.setSnapTime(firsttimesub);
                    photoList.add(userTcPhoto);
//                        if(!imgurl1.equals(""))
//                        {
//                            UserTcPhoto userTcPhoto1 = new UserTcPhoto();
//                            userTcPhoto1.setSnapTime(durationsub);
//                            userTcPhoto1.setUrl(imgurl1);
//                            photoList.add(userTcPhoto1);
//                        }
                    Gson gson = new Gson();
                    String strphotoList = gson.toJson(photoList);
                    LogUtils.e("strphotoList", strphotoList);
                    //  showLoadingDialog("提交中");
                    mProgressDialog = new ProgressDialog(SpecifiedLearningBusinessDetailsActivity.this, ProgressDialog.THEME_HOLO_DARK);
                    mProgressDialog.setMessage("提交中...");
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.show();
//                        mdialog = CustomProgressDialog.show(SpecifiedLearningCourseDetailsActivity.this, "提交中...", false, null);
                    //     new Login().getSureCosrseAndLearn(userId,orgId,tcsn,otcSn,readLength,readInterval,minPer,photoList,this,3);
                    new Login().getSureCosrseAndBusinessLearn(userId, orgId, tcsn, atpSn, atcSn + "", readInterval, minPer, photoList, this, 3);

                }
            }
        } else if (id == R.id.img_course1) {
            if (!isloob) {
                img_course.setText("展开拍照");
                le_course.setVisibility(View.GONE);
                isloob = true;
            } else {
                img_course.setText("收起拍照");
                le_course.setVisibility(View.VISIBLE);
                isloob = false;
            }
        }
    }
     @Override
     public void initData() {
         web = (WebView) findViewById(R.id.wb_course);
         le_parement = (LinearLayout) findViewById(R.id.le_couse);
         img_Courseback = (ImageView) findViewById(R.id.img_Courseback);
         lv_coursedetail = (LinearListView) findViewById(R.id.lv_coursedetail);
         jcVideoPlayerStandard = (MyJZVideoPlayerStandard) findViewById(R.id.videoplayer);
         tv_courseName = (TextView) findViewById(R.id.tv_course);
         tv_courseLength = (TextView) findViewById(R.id.tv_course2);
         le_course = (LinearLayout)findViewById(R.id.le_course);
         tv_cumulativeLength = (TextView)findViewById(R.id.tv_course3);
         show_camera_iv = (ImageView)findViewById(R.id.id_show_camera_iv);
         show_camera_iv1 = (ImageView)findViewById(R.id.id_show_camera_iv1);
         surfaceSv = (SurfaceView)findViewById(R.id.id_area_sv);
         tv_sure = (TextView) findViewById(R.id.tv_course10);
         re_course = (RelativeLayout)findViewById(R.id.re_course);
         img_course = (TextView) findViewById(R.id.img_course1);
         tv_course11 = (TextView)findViewById(R.id.tv_course11);
         mSuperFileView = (SuperFileView2) findViewById(R.id.mSuperFileView);

         StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
         //注册EventBus
         EventBus.getDefault().register(this);
         sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
         sensorEventListener = new Jzvd.JZAutoFullscreenListener();
         Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
         sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
         timer1 = new Timer();
         firsttime = (int)(20+Math.random()*(30-20+1));//第一次拍照随机20秒到30秒
         //第二次验证拍照一分钟之后随机20秒到30秒
         firsttime1 = (int) (80 + Math.random() * (30 - 20 + 1));
         //通过name关键字取出用户名
         Bundle bundle = getIntent().getExtras();
         int     tcsn = bundle.getInt("tcsn");
         int    readInterval = bundle.getInt("readInterval");
         int    minPer = bundle.getInt("minPer");
         String  orgId = bundle.getString("orgId");
         int   atcSn = bundle.getInt("atcSn");
         int   atpSn = bundle.getInt("atpSn");
         List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean> listCourse = (List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean>) bundle.getSerializable("sbcourselist");
         SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                 Context.MODE_PRIVATE);
         SharedPreferences.Editor edit = sp.edit();
         edit.putInt("tcsn",tcsn);
         edit.putInt("readInterval",readInterval);
         edit.putInt("minPer",minPer);
         edit.putString("orgId",orgId);
         edit.putInt("atcSn",atcSn);
         edit.putInt("atpSn",atpSn);
         Gson gson = new Gson();
         String courseStr = gson.toJson(listCourse); //将List转换成Json
         edit.putString("listCourse", courseStr); //存入json串
         edit.commit();




         Thread thread = new Thread(new Runnable() {
             @Override
             public void run() {
                 //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                 mHandler.sendEmptyMessage(0);
             }
         });
         thread.start();
         Thread thread1 = new Thread(new Runnable() {
             @Override
             public void run() {
                 //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                 mHandler.sendEmptyMessage(1);
             }
         });
         thread1.start();
         //摄像头
         int cameraCount = 1;
         Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
         cameraCount = Camera.getNumberOfCameras();// 得到摄像头的个数

         for (int i = 0; i < cameraCount; i++) {
             Camera.getCameraInfo(i, cameraInfo);// 得到每一个摄像头的信息
             // 现在是后置，变更为前置
             if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                 /**
                  * 记得释放camera，方便其他应用调用
                  */
                 releaseCamera();
                 // 打开当前选中的摄像头
                 mCamera = Camera.open(i);
                 //   mCamera.setDisplayOrientation(90);//旋转度数
                 // 通过surfaceview显示取景画面
                 setStartPreview(mCamera, mHolder);

             }
         }
         // 获得句柄
         mHolder = surfaceSv.getHolder();
         // 添加回调
         mHolder.addCallback(this);

     }
    public void initDataSecond() {

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new Jzvd.JZAutoFullscreenListener();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);

        timer1 = new Timer();
        firsttime = (int)(20+Math.random()*(30-20+1));//第一次拍照随机20秒到30秒
        //第二次验证拍照一分钟之后随机20秒到30秒
        firsttime1 = (int) (80 + Math.random() * (30 - 20 + 1));
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                mHandler.sendEmptyMessage(0);
            }
        });
        thread.start();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                mHandler.sendEmptyMessage(1);
            }
        });
        thread1.start();
//        //摄像头
//        int cameraCount = 1;
//        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
//        cameraCount = Camera.getNumberOfCameras();// 得到摄像头的个数
//
//        for (int i = 0; i < cameraCount; i++) {
//            Camera.getCameraInfo(i, cameraInfo);// 得到每一个摄像头的信息
//            // 现在是后置，变更为前置
//            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
//                /**
//                 * 记得释放camera，方便其他应用调用
//                 */
//                releaseCamera();
//                // 打开当前选中的摄像头
//                mCamera = Camera.open(i);
//                //   mCamera.setDisplayOrientation(90);//旋转度数
//                // 通过surfaceview显示取景画面
//                setStartPreview(mCamera, mHolder);
//
//            }
//        }
//        // 获得句柄
//        mHolder = surfaceSv.getHolder();
//        // 添加回调
//        mHolder.addCallback(this);
    }
    @Override
    public void onFailure(Call call, int what) {
        super.onFailure(call, what);
        if(what==3)
        {
            mProgressDialog.dismiss();
            Toast.makeText(SpecifiedLearningBusinessDetailsActivity.this,"提交失败，重新提交",Toast.LENGTH_LONG).show();
        }

    }



    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if(what==3)
        {
            SignBean signBean = JSON.parseObject(result, SignBean.class);
            SignBean.DataBean data = signBean.getData();
            if(data.getFinishMark()==0)//未完成
            {
                mProgressDialog.dismiss();
                SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                        Context.MODE_PRIVATE);
                String   courseStr = sp.getString("listCourse","");  //取出key为"KEY_PEOPLE_DATA"的值，如果值为空，则将第二个参数作为默认值赋值
                Gson gson = new Gson();
                //将json字符串转换成 people对象
                final   List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean> CourseDetailList = gson.fromJson(courseStr, new TypeToken<List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean>>() {
                }.getType());
                if(CourseDetailList.size()>0)
                {
                    timerTask.cancel();
                    timer1.cancel();
                    timerTask=null;
                    timer1=null;
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    View view = View
                            .inflate(SpecifiedLearningBusinessDetailsActivity.this, R.layout.diolog_learn_layout, null);
                    TextView tv_message= (TextView) view
                            .findViewById(R.id.message);//输入内容
                    tv_message.setText("您好!当前课程学完了,是否想学习下一课程");
                    TextView btn_sure = (TextView) view.findViewById(R.id.positiveButton);
                    TextView btn_cancel = (TextView) view.findViewById(R.id.negativeButton);
                    btn_sure.setText("学习");
                    btn_cancel.setText("离开");
                    final    AlertDialog dialog = builder.create();
                    dialog.show();
                    dialog.getWindow().setContentView(view);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.setCancelable(false);
                    btn_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sp.edit();
                            editor.remove("imgurl");
                            editor.remove("format");
                            editor.commit();
                            //设置你的操作事项
                            int tcSn = CourseDetailList.get(0).getTcSn();
                            int atcSn = CourseDetailList.get(0).getSn();


                            SharedPreferences.Editor edit = sp.edit();
                            edit.putInt("atcSn",atcSn);
                            edit.putInt("tcsn",tcSn);
                            ArrayList<SpecifiedLearningBusinessBean.RowsBean.CourseListBean> CourseList=new ArrayList<>();
                            CourseList.clear();
                            for (int i = 0;i < CourseDetailList.size(); i++) {
                                if (CourseDetailList.get(i).getSn() != atcSn) {
                                    CourseList.add(CourseDetailList.get(i));
                                }

                            }
                            Gson gson = new Gson();
                            String courseStr = gson.toJson(CourseList); //将List转换成Json
                            edit.putString("listCourse", courseStr); //存入json串
                            edit.commit();

                            show_camera_iv.setWillNotDraw(true);//清除图片内容
                            initcourseData();  //根据课程序列号查询课程详情
                            initcoursesubject(); //根据课程序列号查询测验题
                            initDataSecond();//初始化
                        }
                    });
                    btn_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
//                            SharedPreferences spp = getSharedPreferences("imgurl",
//                                    Context.MODE_PRIVATE);
//                            SharedPreferences.Editor editor = spp.edit();
//                            editor.clear();
//                            editor.commit();
                            SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor edit = sp.edit();
                            edit.clear();
                            edit.commit();
                            finish();
                        }
                    });
                }else if(CourseDetailList.size()==0)
                {
                    timerTask.cancel();
                    timer1.cancel();
                    timerTask=null;
                    timer1=null;
//                    SharedPreferences spp = getSharedPreferences("imgurl",
//                            Context.MODE_PRIVATE);
//                    SharedPreferences.Editor editor = spp.edit();
//                    editor.clear();
//                    editor.commit();
                    SharedPreferences sp1 = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp1.edit();
                    edit.clear();
                    edit.commit();
                    finish();
                    showToast("该课程提交成功");
                }

            }else if( data.getFinishMark()==1)//已完成未签名
            {
                timerTask.cancel();
                timer1.cancel();
                timerTask=null;
                timer1=null;
//                SharedPreferences spp = getSharedPreferences("imgurl",
//                        Context.MODE_PRIVATE);
//                SharedPreferences.Editor editor = spp.edit();
//                editor.clear();
//                editor.commit();
                SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                int sn = data.getSn();
                Bundle bundle = new Bundle();
                bundle.putInt("sn", sn);
                bundle.putString("signPicUrl", "");
                bundle.putInt("signMark",1);
                startActivity(SignActivity.class, bundle);
                mProgressDialog.dismiss();
                finish();
                showToast("该课程提交成功");
            }else if(data.getFinishMark()==2)
            {
                timerTask.cancel();
                timer1.cancel();
                timerTask=null;
                timer1=null;
//                SharedPreferences spp = getSharedPreferences("imgurl",
//                        Context.MODE_PRIVATE);
//                SharedPreferences.Editor editor = spp.edit();
//                editor.clear();
//                editor.commit();
                SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                mProgressDialog.dismiss();
                finish();
                showToast("该课程提交成功");
            }
        }

        super.onSuccess(result, call, response, what);
    }
    @Override
    public void onError(String result, Call call, Response response, int what) {
        if(what==3)
        {
            mProgressDialog.dismiss();
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();;
                    //设置你的操作事项
                }
            });
            builder1.create().show();

        }

        super.onError(result, call, response, what);
    }


    @Override
     public void requestData() {
        initcourseData();
        initcoursesubject();
     }
    //根据课程序列号查询测验题
    private void initcoursesubject() {
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                Context.MODE_PRIVATE);
        int tcsn = sp.getInt("tcsn", 0);
        OkGo.get(AppInterfaceConfig.BASE_URL + "course/question/" + tcsn)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {
                        CourseDetailSubjectBean courseDetailSubjectBean = JSON.parseObject(result, CourseDetailSubjectBean.class);
                        List<CourseDetailSubjectBean.RowsBean> rowsList = courseDetailSubjectBean.getRows();
                        if(rowsList.size()==0)
                        {
                            tv_course11.setVisibility(View.GONE);
                            lv_coursedetail.setAdapter(null);
                            return;
                        }
                        rowscourseList.clear();
                        rowscourseList.addAll(rowsList);
                        tv_course11.setVisibility(View.VISIBLE);
                        courseDetailSubjectApt = new CourseDetailSubjectApt(SpecifiedLearningBusinessDetailsActivity.this, rowscourseList, R.layout.course_detail_item);
                        lv_coursedetail.setAdapter(courseDetailSubjectApt);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        showToast("网络连接错误");
                    }
                });
    }

    //根据课程序列号查询课程详情
    private void initcourseData() {
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                Context.MODE_PRIVATE);
        int tcsn = sp.getInt("tcsn", 0);
        OkGo.get(AppInterfaceConfig.BASE_URL + "course/course/" + tcsn)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {

                        CourseDetailBean courseDetailBean = JSON.parseObject(result, CourseDetailBean.class);
                        CourseDetailBean.DataBean coursedata = courseDetailBean.getData();
                        String courseName = coursedata.getCourseName();//课程名称
                        if(courseName==null)
                        {
                            return;
                        }
                        //课程时长
                        int   courseLength = coursedata.getCourseLength();
                        SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                                Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        //    editor.putString("duration", duration);
                        editor.putInt("courseLength", courseLength);
                        editor.commit();

                        tv_courseName.setText(courseName);
                        tv_courseLength.setText("课程时长:" + courseLength + "分钟");
                        //视频地址
                        String accessVideoUrl = coursedata.getAccessVideoUrl();

                        video(accessVideoUrl);
                        if(courseLength ==0)
                        {
                            return;
                        }
                        //课长判断何久拍照
                        photo(courseLength);

                        //PDF文件解析
                        String fileUrl = coursedata.getFileUrl();
                        String fileName = coursedata.getFileName();
                        if (fileUrl != null) {
                            mSuperFileView.setVisibility(View.VISIBLE);
                            mSuperFileView.setOnGetFilePathListener(new SuperFileView2.OnGetFilePathListener() {
                                @Override
                                public void onGetFilePath(SuperFileView2 mSuperFileView2) {
                                    String path = FileParseUtil.getFilePath(mSuperFileView2, fileUrl, fileName);
                                    if (path.contains("http")) {//网络地址要先下载
                                        showAlertDialog(mSuperFileView2, fileUrl);
                                    } else {
                                        mSuperFileView2.displayFile(new File(path));
                                    }
                                }
                            });
                            mSuperFileView.show();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        showToast("网络连接错误");
                    }
                });
    }
    private void photo(int courseLength) {
        LoginUserBean userInfo = UserManger.getUserInfo();
//        Integer minPer = userInfo.getMinPer();//所属行政区划学习时长最低百分比
        SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                Context.MODE_PRIVATE);
        int minPer = sp.getInt("minPer", 0);
        int num = (courseLength * 60 * minPer) / 100;

        SharedPreferences.Editor editor = sp.edit();
        //    editor.putString("duration", duration);
        editor.putInt("num", num);
        editor.commit();


    }
    private void video(String accessVideoUrl) {
        if (accessVideoUrl == null) {
            jcVideoPlayerStandard.setVisibility(View.GONE);
                 return;
        }
        jcVideoPlayerStandard.setVisibility(View.VISIBLE);
        HashMap headers = new HashMap<String, String>();
        headers.put("Referer",AppInterfaceConfig.BASE_URL);
        JZDataSource jzDataSource=new JZDataSource(accessVideoUrl,"",headers);
        jcVideoPlayerStandard.setUp(jzDataSource,jcVideoPlayerStandard.SCREEN_NORMAL);
        //jcVideoPlayerStandard.setUp(accessVideoUrl,"", jcVideoPlayerStandard.SCREEN_NORMAL, JZMediaIjk.class);
       // jcVideoPlayerStandard.startVideo();//自动播放
        Picasso.with(getApplicationContext()).load(R.mipmap.video)
                .into(jcVideoPlayerStandard.thumbImageView);
        JzvdStd.progressBar.setEnabled(false);//禁止拖动
      //  JZVideoPlayer.setJzUserAction(new MyUserActionStandard());

    }

    /**
     * 这只是给埋点统计用户数据用的，不能写和播放相关的逻辑，监听事件请参考MyJZVideoPlayerStandard，复写函数取得相应事件
     */
//    class MyUserActionStandard implements JZUserActionStandard {
//
//        @Override
//        public void onEvent(int type, Object url, int screen, Object... objects) {
//            switch (type) {
//                case JZUserAction.ON_CLICK_START_ICON:
//                    Log.i("USER_EVENT", "ON_CLICK_START_ICON" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_CLICK_START_ERROR:
//                    Log.i("USER_EVENT", "ON_CLICK_START_ERROR" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_CLICK_START_AUTO_COMPLETE:
//                    Log.i("USER_EVENT", "ON_CLICK_START_AUTO_COMPLETE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_CLICK_PAUSE:
//                    Log.i("USER_EVENT", "ON_CLICK_PAUSE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_CLICK_RESUME:
//                    Log.i("USER_EVENT", "ON_CLICK_RESUME" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_SEEK_POSITION:
//                    Log.i("USER_EVENT", "ON_SEEK_POSITION" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_AUTO_COMPLETE:
//                    Log.i("USER_EVENT", "ON_AUTO_COMPLETE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_ENTER_FULLSCREEN:
//                    Log.i("USER_EVENT", "ON_ENTER_FULLSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_QUIT_FULLSCREEN:
//                    Log.i("USER_EVENT", "ON_QUIT_FULLSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_ENTER_TINYSCREEN:
//                    Log.i("USER_EVENT", "ON_ENTER_TINYSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_QUIT_TINYSCREEN:
//                    Log.i("USER_EVENT", "ON_QUIT_TINYSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME:
//                    Log.i("USER_EVENT", "ON_TOUCH_SCREEN_SEEK_VOLUME" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_TOUCH_SCREEN_SEEK_POSITION:
//                    Log.i("USER_EVENT", "ON_TOUCH_SCREEN_SEEK_POSITION" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//
//                case JZUserActionStandard.ON_CLICK_START_THUMB:
//                    Log.i("USER_EVENT", "ON_CLICK_START_THUMB" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserActionStandard.ON_CLICK_BLANK:
//                    Log.i("USER_EVENT", "ON_CLICK_BLANK" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                default:
//                    Log.i("USER_EVENT", "unknow");
//                    break;
//            }
//        }
//    }

    @SuppressLint("HandlerLeak")
    private void initDialog() {
        //设置contentView
        View contentView = LayoutInflater.from(SpecifiedLearningBusinessDetailsActivity.this).inflate(R.layout.course_popwindowlayout, null);
        mPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);

        //倒计时
        downtime = (TextView)contentView.findViewById(R.id.tv_photo3);
        TextPaint paint = downtime.getPaint();
        paint.setFakeBoldText(true);//字体加粗
        ImageView takepciture = (ImageView)contentView.findViewById(R.id.img_photo1);//点拍照
        //    LinearLayout le_takepicture = (LinearLayout)contentView.findViewById(R.id.le_takepicture);//跟布局
        takepciture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mOffTime.cancel();
                mPopWindow.dismiss();
                startActivityForResult(TakePhotoActivity.class,null, 0);
            }
        });

//        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                // popupWindow隐藏时恢复屏幕正常透明度
//                setBackgroundAlpha(1.0f);
//            }
//        });
//        setBackgroundAlpha(0.35f);//设置屏幕透明度
//        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setFocusable(false);
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.showAtLocation(le_parement, Gravity.CENTER, 0, 0);
        //////倒计时
        mOffTime = new Timer(true);
        TimerTask tt = new TimerTask() {
            int countTime = 15;

            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                mOffHandler.sendMessage(msg);

            }
        };
        mOffTime.schedule(tt, 1000, 1000);
    }

    @SuppressLint("HandlerLeak")
    private void initDialog2() {
        //设置contentView
        View contentView = LayoutInflater.from(SpecifiedLearningBusinessDetailsActivity.this).inflate(R.layout.test_popwindowlayout, null);
        mPopWindow2 = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);


        ImageView takepciture = (ImageView)contentView.findViewById(R.id.img_photo1);//点拍照
        LinearLayout le_takepicture = (LinearLayout)contentView.findViewById(R.id.le_takepicture1);//跟布局
        takepciture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mPopWindow2.dismiss();
                startActivityForResult(TakePhotoActivity.class,null, 0);
            }
        });

//        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                // popupWindow隐藏时恢复屏幕正常透明度
//                setBackgroundAlpha(1.0f);
//            }
//        });
//        setBackgroundAlpha(0.35f);//设置屏幕透明度
//        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow2.setFocusable(false);
        mPopWindow2.setOutsideTouchable(false);
        mPopWindow2.showAtLocation(le_takepicture, Gravity.CENTER, 0, 0);

    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event){
        if(mPopWindow!=null&&mPopWindow.isShowing()){
            return false;
        }
        if(mSorryPopWindow!=null&&mSorryPopWindow.isShowing()){
            return false;
        }
        if(mPopWindow2!=null&&mPopWindow2.isShowing()){
            return false;
        }

        return super.dispatchTouchEvent(event);
    }

    private void ShowSorryPopwindow() {

        View contentView = LayoutInflater.from(SpecifiedLearningBusinessDetailsActivity.this).inflate(R.layout.sorry_popwindowlayout, null);
        mSorryPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        //   LinearLayout le_sorry = (LinearLayout)contentView.findViewById(R.id.le_sorry);//跟布局
        ImageView sorry_exit = (ImageView)contentView.findViewById(R.id.sorry_img_photo1);//退出
        sorry_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSorryPopWindow.dismiss();
                SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.remove("format");
                edit.commit();
                Thread thread2 = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                        mHandler.sendEmptyMessage(0);
                    }
                });
                thread2.start();

            }
        });
//        mSorryPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                // popupWindow隐藏时恢复屏幕正常透明度
//                setBackgroundAlpha(1.0f);
//            }
//        });
//        setBackgroundAlpha(0.35f);//设置屏幕透明度
        //      mSorryPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mSorryPopWindow.setFocusable(false);
        mSorryPopWindow.setOutsideTouchable(false);
        mSorryPopWindow.showAtLocation(le_parement, Gravity.CENTER, 0, 0);

    }
    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        TiShiDialog.Builder builder = new TiShiDialog.Builder(this);
        builder.setMessage("点放弃,将自动放弃本课程学习记录");
        builder.setTitle("提示:");
        builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
//                SharedPreferences spp = getSharedPreferences("imgurl",
//                        Context.MODE_PRIVATE);
//                SharedPreferences.Editor editor = spp.edit();
//                editor.clear();
//                editor.commit();
                SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                timerTask.cancel();
                timer1.cancel();
                timerTask=null;
                timer1=null;
                dialog.dismiss();
                finish();
                //设置你的操作事项

            }
        });

        builder.setNegativeButton("取消",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();

        //   super.onBackPressed();
    }





    @Override
    protected void onPause() {
        super.onPause();
        if(sensorManager!=null){
            sensorManager.unregisterListener(sensorEventListener);
        }

//        JZVideoPlayer jzvd = JZVideoPlayerManager.getCurrentJzvd();
//         if(jzvd!=null)
//         {
//            jzvd.onStatePause();
//            JZMediaManager.pause();//暂停
//
//         }else{
//
//                 JZVideoPlayer.releaseAllVideos();
//
//     }

        Jzvd.resetAllVideos();


        /**
         * 记得释放camera，方便其他应用调用
         */
        releaseCamera();
    }



    @Override
    public void onStart() {
        super.onStart();
        if (this.checkCameraHardware(this) && (mCamera == null)) {
            // 打开camera
            mCamera = getCamera();
            if (mHolder != null) {
                setStartPreview(mCamera, mHolder);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //摄像头
        int cameraCount = 1;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();// 得到摄像头的个数

        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);// 得到每一个摄像头的信息
            // 现在是后置，变更为前置
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                /**
                 * 记得释放camera，方便其他应用调用
                 */
                releaseCamera();
                // 打开当前选中的摄像头
                mCamera = Camera.open(i);
                //   mCamera.setDisplayOrientation(90);//旋转度数
                // 通过surfaceview显示取景画面
                setStartPreview(mCamera, mHolder);

            }
        }




    }


    private Camera getCamera() {
        Camera camera = null;
        try {
            camera = Camera.open();
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            camera = null;
            LogUtils.e(TAG, "Camera is not available (in use or does not exist)");
        }
        return camera;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        FileParseUtil.releaseFileView();

        if(mPopWindow != null) {

            mPopWindow.dismiss();
        }
        if(mSorryPopWindow != null) {

            mSorryPopWindow.dismiss();
        }
        if(mPopWindow2 != null) {

            mPopWindow2.dismiss();
        }
        if(mProgressDialog != null ){
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
        mHandler.removeCallbacksAndMessages(null);
        mOffHandler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);//反注册EventBus
        SharedPreferences sp = getSharedPreferences("CameraSwitchView",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        String imgurl = event.getMessage();
        String messageurl = event.getMessageurl();
        boolean isphoto = event.isIsphoto();

        if (isphoto) {
            show_camera_iv.setWillNotDraw(false);
            show_camera_iv.setContentDescription(messageurl);
            Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(messageurl);
            show_camera_iv.setImageBitmap(bitmapByUrl);
            SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString("imgurl", imgurl);
            edit.commit();
        } else {
            show_camera_iv.setWillNotDraw(true);
            SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString("imgurl", "");
            edit.commit();
            Toast.makeText(SpecifiedLearningBusinessDetailsActivity.this, "照片上传失败", Toast.LENGTH_LONG).show();
        }
    }
        /**
     * 释放mCamera
     */
    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();// 停掉原来摄像头的预览
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        setStartPreview(mCamera, mHolder);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null) {
            // preview surface does not exist
            return;
        }
        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }

        setStartPreview(mCamera, mHolder);

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // 当surfaceview关闭时，关闭预览并释放资源
        /**
         * 记得释放camera，方便其他应用调用
         */
        releaseCamera();
        holder = null;
        surfaceSv = null;
    }



    /**
     * 创建png图片回调数据对象
     */
//    Camera.PictureCallback picture = new Camera.PictureCallback() {
//        @Override
//        public void onPictureTaken(byte[] data, Camera camera) {
//            File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
//            if (pictureFile == null) {
//                Log.d(TAG,
//                        "Error creating media file, check storage permissions: ");
//                return;
//            }
//            try {
//                FileOutputStream fos = new FileOutputStream(pictureFile);
//                fos.write(data);
//                fos.close();
//                FileInputStream fis = new FileInputStream(pictureFile);
//                Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
//                bitmapByUrl = compressScale(bitmapByUrl);
//                bitmapByUrl = rotaingImageView(-90, bitmapByUrl);
//
//                SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss ");
//                Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间
//                String str = formatter.format(curDate);
//                Bitmap bitmap = ImageUtil.drawTextToLeftBottom(SpecifiedLearningCourseDetailsActivity.this, bitmapByUrl, str, 8, Color.RED, 1, 1);
//
//                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pictureFile));
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
//                bos.flush();
//                bos.close();
//
//                returnResult(pictureFile);
//            } catch (FileNotFoundException e) {
//                Log.d(TAG, "File not found: " + e.getMessage());
//            } catch (IOException e) {
//                Log.d(TAG, "Error accessing file: " + e.getMessage());
//            }
//        }
//    };

    /**
     * 图片按比例大小压缩方法
     *
     * @param image （根据Bitmap图片压缩）
     * @return
     */
//    public static Bitmap compressScale(Bitmap image) {
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//        // 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
//        if (baos.toByteArray().length / 1024 > 1024) {
//            baos.reset();// 重置baos即清空baos
//            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%，把压缩后的数据存放到baos中
//        }
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
//        BitmapFactory.Options newOpts = new BitmapFactory.Options();
//        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
//        newOpts.inJustDecodeBounds = true;
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
//        newOpts.inJustDecodeBounds = false;
//        int w = newOpts.outWidth;
//        int h = newOpts.outHeight;
//        Log.i(TAG, w + "---------------" + h);
//        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
//        // float hh = 800f;// 这里设置高度为800f
//        // float ww = 480f;// 这里设置宽度为480f
//        float hh = 600f;
//        float ww = 450f;
//        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
//        int be = 1;// be=1表示不缩放
//        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
//            be = (int) (newOpts.outWidth / ww);
//        } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
//            be = (int) (newOpts.outHeight / hh);
//        }
//        if (be <= 0)
//            be = 1;
//        newOpts.inSampleSize = be; // 设置缩放比例
//        // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
//        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
//        isBm = new ByteArrayInputStream(baos.toByteArray());
//        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
//        return bitmap;
//        //return bitmap;
//    }

    //图片旋转
//    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
//        //旋转图片 动作
//        Matrix matrix = new Matrix();
//        ;
//        matrix.postRotate(angle);
//        System.out.println("angle2=" + angle);
//        // 创建新的图片
//        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
//                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//        return resizedBitmap;
//    }


    /**
     * Create a File for saving an image or video
     */
//    private static File getOutputMediaFile(int type) {
//        // To be safe, you should check that the SDCard is mounted
//        // using Environment.getExternalStorageState() before doing this.
//
//        File mediaStorageDir = new File(
//                Environment
//                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
//                "MyCameraApp");
//        // This location works best if you want the created images to be shared
//        // between applications and persist after your app has been uninstalled.
//
//        // Create the storage directory if it does not exist
//        if (!mediaStorageDir.exists()) {
//            if (!mediaStorageDir.mkdirs()) {
//                Log.d("MyCameraApp", "failed to create directory");
//                return null;
//            }
//        }
//        // Create a media file name
//        String timeStamp = HelpUtil.getDateFormatString(new Date());
//        File mediaFile;
//        if (type == MEDIA_TYPE_IMAGE) {
//            mediaFile = new File(mediaStorageDir.getPath() + File.separator
//                    + "IMG_" + timeStamp + ".png");
//        } else {
//            return null;
//        }
//        return mediaFile;
//    }

    /**
     * Check if this device has a camera
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }
    /*****
     * 接受第二个Activity返回的数据时调用
     *
     * ****/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String url = data.getStringExtra("url");
        // 根据返回码的不同，设置参数
        if (requestCode == 0) {
            if(resultCode==1) {
                if (url != null && !TextUtils.isEmpty(url)) {
//                    show_camera_iv.setWillNotDraw(false);//从新添加图片内容
//                    show_camera_iv.setContentDescription(url);
//                    Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
//                    show_camera_iv.setImageBitmap(bitmapByUrl);
                    SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
                            Context.MODE_PRIVATE);
                    String stringTime = sp.getString("format", "");
                    int index1 = stringTime.indexOf(":");
                    int index2 = stringTime.indexOf(":", index1 + 1);
                    int hh = Integer.parseInt(stringTime.substring(0, index1));
                    int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
                    int ss = Integer.parseInt(stringTime.substring(index2 + 1));
                    int formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
                    subformatTurnSecond = formatTurnSecond+1 ;
                    String stringTime1 = getStringTime(subformatTurnSecond);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("format", stringTime1);
                    edit.commit();
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                            mHandler.sendEmptyMessage(0);
                        }
                    });
                    thread.start();






//                    timerTask = new TimerTask() {
//                        @Override
//                        public void run() {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    String stringTime1 = getStringTime(subformatTurnSecond++);
//                                    tv_cumulativeLength.setText(stringTime1);
//                                    SharedPreferences sp = getSharedPreferences("SpecifiedLearningBusinessDetailsActivity",
//                                            Context.MODE_PRIVATE);
//                                    SharedPreferences.Editor edit = sp.edit();
//                                    edit.putString("format", stringTime1);
//                                    edit.commit();
//                                    int courseLength = sp.getInt("courseLength", 0);
//                                    int courseLengthtime = courseLength * 60;
//                                    String courseLengthtime1 = getStringTime(courseLengthtime);
//                                    LogUtils.e("累计时间",courseLengthtime1);
//                                    if(stringTime1.equals(courseLengthtime1))
//                                    {
//                                        edit.putString("format", stringTime1);
//                                        edit.commit();
//                                        timerTask.cancel();
//
//                                    }
//
//                                }
//                            });
//                        }
//                    };
//                    timer1.schedule(timerTask, 0, 1000);

//                    if(show_camera_iv.getDrawable() == null)
//                    {
//                        show_camera_iv.setContentDescription(url);
//                        Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
//                        show_camera_iv.setImageBitmap(bitmapByUrl);
//                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                Context.MODE_PRIVATE);
//                        String stringTime = sp.getString("format", "");
//                        int index1 = stringTime.indexOf(":");
//                        int index2 = stringTime.indexOf(":", index1 + 1);
//                        int hh = Integer.parseInt(stringTime.substring(0, index1));
//                        int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
//                        int ss = Integer.parseInt(stringTime.substring(index2 + 1));
//                        int  formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
//                        subformatTurnSecond = formatTurnSecond - 2;//处理拍照时延迟2秒
//                        timerTask = new TimerTask() {
//                            @Override
//                            public void run() {
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        String stringTime1 = getStringTime(subformatTurnSecond++);
//                                        tv_cumulativeLength.setText(stringTime1);
//                                        SharedPreferences sp = getSharedPreferences("durationandformat",
//                                                Context.MODE_PRIVATE);
//                                        SharedPreferences.Editor edit = sp.edit();
//                                        edit.putString("format", stringTime1);
//                                        edit.commit();
//                                        String duration = sp.getString("duration", "");
//
//                                        if(stringTime1.equals(duration))
//                                        {
//                                            timerTask.cancel();
//
//                                            startActivityForResult(TakePhotoActivity.class,null, 0);
//                                        }
//
//                                    }
//                                });
//                            }
//                        };
//                        timer1.schedule(timerTask,0,1000);
//
//
//                    }else{
//                        show_camera_iv1.setContentDescription(url);
//                        Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
//                        show_camera_iv1.setImageBitmap(bitmapByUrl);
//
//                    SharedPreferences sp = getSharedPreferences("durationandformat",
//                            Context.MODE_PRIVATE);
//                    String stringTime = sp.getString("format", "");
//                    int index1 = stringTime.indexOf(":");
//                    int index2 = stringTime.indexOf(":", index1 + 1);
//                    int hh = Integer.parseInt(stringTime.substring(0, index1));
//                    int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
//                    int ss = Integer.parseInt(stringTime.substring(index2 + 1));
//                    int   formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
//                    subformatTurnSecond = formatTurnSecond - 2;//处理拍照时延迟2秒
//                    timerTask = new TimerTask() {
//                        @Override
//                        public void run() {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    String stringTime1 = getStringTime(subformatTurnSecond++);
//                                    tv_cumulativeLength.setText(stringTime1);
//                                    SharedPreferences sp = getSharedPreferences("durationandformat",
//                                            Context.MODE_PRIVATE);
//                                    SharedPreferences.Editor edit = sp.edit();
//                                    edit.putString("format", stringTime1);
//                                    edit.commit();
//
//                                }
//                            });
//                        }
//                    };
//                    timer1.schedule(timerTask,0,1000);
//                    }
//                }

//                    int hour = (int) ((tv_cumulativeLength.getBase() + (SystemClock.elapsedRealtime() - mRecordTime)) / 1000 / 60);
//                    tv_cumulativeLength.setFormat("0" + String.valueOf(hour) + ":%s");
//                    tv_cumulativeLength.start();
                }

            }

        }
    }




//    /**
//     * 将String类型的时间转换成long,如：12:01:08
//     * @param strTime String类型的时间
//     * @return long类型的时间
//     * */
//    protected long convertStrTimeToLong(String strTime) {
//        // TODO Auto-generated method stub
//        String []timeArry=strTime.split(":");
//        long longTime=0;
//        if (timeArry.length==2) {//如果时间是MM:SS格式
//            longTime=Integer.parseInt(timeArry[0])*1000*60+Integer.parseInt(timeArry[1])*1000;
//        }else if (timeArry.length==3){//如果时间是HH:MM:SS格式
//            longTime=Integer.parseInt(timeArry[0])*1000*60*60+Integer.parseInt(timeArry[1])
//                    *1000*60+Integer.parseInt(timeArry[0])*1000;
//        }
//        return SystemClock.elapsedRealtime()-longTime;
//    }
//    /**
//     * activity返回式返回拍照图片路径
//     *
//     * @param mediaFile
//     */
//    private void returnResult(File mediaFile) {
//
//        Uri uri = Uri.fromFile(mediaFile);
//        String url = uri.toString().substring(uri.toString().indexOf("///") + 2);
//
//        if (url != null && !TextUtils.isEmpty(url)) {
//            show_camera_iv.setContentDescription(url);
//            Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(url);
//            show_camera_iv.setImageBitmap(bitmapByUrl);
//            mCamera.startPreview();
//        }
//        uploadImg(mediaFile);
//
//    }

//    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
//    private final OkHttpClient client = new OkHttpClient();
//
//    private void uploadImg(File mediaFile) {
//
//        // mImgUrls为存放图片的url集合
//        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//
//        if (mediaFile != null) {
//            builder.addFormDataPart("headImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
//        }
//
//
//        MultipartBody requestBody = builder.build();
//        //构建请求
//        Request request = new Request.Builder()
//                .url(AppInterfaceConfig.BASE_URL + "app/course/uploadFromApp")//地址
//                .post(requestBody)//添加请求体
//                .build();
//
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                LogUtils.e("上传失败", e.getLocalizedMessage());
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//
//                String str = response.body().string();
//                LogUtils.e("上传成功", str);
//                UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
//                String data = upPhotoBean.getData();
//                SharedPreferences sp = getSharedPreferences("imgurl",
//                        Context.MODE_PRIVATE);
//                SharedPreferences.Editor editor = sp.edit();
//                editor.putString("imgurl", data);
//                editor.commit();
//
//                //       Picasso.with(CourseDetailsActivity.this).load(Uri.parse(data)).into(show_camera_iv);//加载图片
//                LogUtils.e("上传图片", data);
//
//            }
//        });
//
//    }


    /**
     * 设置camera显示取景画面,并预览
     *
     * @param camera
     */
    private void setStartPreview(Camera camera, SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(holder);
            //开始预览
            camera.setDisplayOrientation(90);
            camera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    private void showAlertDialog(SuperFileView2 superFileView2, String url) {
        //1、使用Dialog、设置style
        //2、设置布局

        View contentView = LayoutInflater.from(SpecifiedLearningBusinessDetailsActivity.this).inflate(R.layout.dialog_circle, null);
        mDownloadPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);

        mDownloadPopWindow.setContentView(contentView);
        mDownloadPopWindow.setFocusable(false);
        mDownloadPopWindow.setOutsideTouchable(false);
        mDownloadPopWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);


        CircularProgressView circularProgressView = contentView.findViewById(R.id.circleProgress);
        TextView textView = contentView.findViewById(R.id.progressTxt);
        TextView textView1 = contentView.findViewById(R.id.hintTxt);

        jumpingBeans2 = JumpingBeans.with(textView1)
                .makeTextJump(0, textView1.getText().length())
                .setIsWave(true)
                .setLoopDuration(3000)
                .build();

        downLoadFromNet(url, superFileView2, circularProgressView, textView);
    }

    private void downLoadFromNet(final String url, final SuperFileView2 superFileView, CircularProgressView circularProgressView, TextView tv1) {
        //showLoadingDialog("文件下载中...");
        //1.网络下载、存储路径、
        File cacheFile = FileParseUtil.getCacheFile(url);
        if (cacheFile.exists()) {
            if (cacheFile.length() <= 0) {
                cacheFile.delete();
                return;
            }
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功,从服务器的响应对象中获取apk,流(服务器 输入流(提供数据)  本地 输出流(写入文件))
                ResponseBody body = response.body();
                //告知progressDialog总进度,不变
                //progressDialog.setMax((int) body.contentLength());
                final int allLength = (int) body.contentLength();
                //inputStream就是服务器把需要下载的apk以流的形式提供给客户端
                InputStream inputStream = body.byteStream();

                String fileName = url.substring(url.lastIndexOf("/"));
                String directory = Environment.getExternalStoragePublicDirectory
                        (Environment.DIRECTORY_DOWNLOADS).getPath();
                //File file = new File(directory+fileName);

                File file = FileParseUtil.getCacheFile(url);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                int temp = 0;//用于记录目前下载的到的位置
                while ((len = inputStream.read(bytes)) != -1) {
                    //将读过的数据写入文件中
                    fos.write(bytes, 0, len);
                    //告知progressDialog在下载过程中的当前进度
                    temp += len;
                    //将当前的下载位置,设置给progressDialog
                    //progressDialog.setProgress(temp);
                    //没下载一段数据,睡眠一段时间

                    int progress = (int) (temp * 100.0 / allLength);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            circularProgressView.setProgress(progress);
                            tv1.setText(progress + "%");
                        }
                    });

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //2.ACache记录文件的有效期
                        mDownloadPopWindow.dismiss();
                        superFileView.displayFile(file);
                    }
                });
            }
        });
    }
}
